<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./vue.js"></script>
    <style>
        *{
            padding:0;
            margin:0;
        }
        p{
            border:1px solid green;
        }
        p.active{
            background: gray;
        }
    </style>
</head>
<body>
<div id="root">
    <form action="https://www.baidu.com/s" target="_blank">
        <input v-model="wd" @keydown.40.38="pHandler" @input="search" type="text" autocomplete="off" name="wd"/>
    </form>
    <p :class="{active:activeIndex===index}" v-for="(item,index) in g" :key="item.sa">{{item.q}}</p>
</div>
</body>
<script type="module">
    import jsonp from "./jsonp.js";
    Vue.prototype.$jsonp = jsonp;
    // https://www.baidu.com/sugrec?prod=pc&wd=1&cb=jQuery110203078381282478101_
    new Vue({
        el:"#root",
        data:{
            activeIndex:-1,
            wd:"",
            g:[],
            q:"",
            isRender:false
        },
        methods:{
            pHandler(e){
                if(e.keyCode===40){
                    console.log("向下")
                    this.activeIndex++;
                    if(this.activeIndex> this.g.length-1){
                        this.activeIndex=-1;
                    }
                }else{
                    this.activeIndex--;
                    if(this.activeIndex<-1) this.activeIndex = this.g.length-1;
                }
                if(this.activeIndex !== -1){
                    this.wd = this.g[this.activeIndex].q;
                }else{
                    this.wd =this.q;
                }
            },
            async search(e){
                if(this.timer) clearTimeout(this.timer);
                this.timer = setTimeout(async ()=>{
                    const result = await this.$jsonp({
                        url:"https://www.baidu.com/sugrec",
                        params:{
                            prod:"pc",
                            wd:e.target.value.trim()
                        },
                        jsonp:"cb"
                    });
                    this.g = Array.isArray(result.g)?result.g:[];
                    this.q = result.q;
                },300)

            }
        }
    })
</script>
</html>